import request from "@/utils/request";
import host from "@/utils/host";
import axios from "axios";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style

export default {
  /**
   * 分页加模糊查询
   * @param {当前页} currentPage
   * @param {每页列表数} pageSize
   * @param {模糊查询参数，为文件名} name
   * @returns
   */
  getList(name) {
    return request({
      url: `/file/search`,
      method: "get",
      params: { name }, // 使用查询参数传递数据
    });
  },
  /**
   * 模糊查询获取总数
   * @param {文件名} name
   * @returns
   */
  getTotal(name) {
    return request({
      url: `/file/total`,
      method: "get",
      params: { name },
    });
  },
  /**
   * 下载文件
   * @param {文件名} name
   */
  download(fullPath, name) {
    const url = `http://${host}/tran/file/download`;
    NProgress.start();
    // 请求体参数
    const params = {
      path: fullPath, // 传递完整文件路径
    };
    axios
      .post(url, params, {
        responseType: "blob", // 指定响应类型为二进制数据
      })
      .then((response) => {
        const blob = new Blob([response.data], {
          type: "text/plain",
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", name);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        NProgress.done();
      })
      .catch((error) => {
        console.error(error);
      });
  },
  /**
   * 删除文件
   * @param {文件名} name
   * @returns
   */
  delete(param) {
    return request({
      url: `/file/delete`,
      method: "post",
      data: {
        path: param,
      },
    });
  },
  /**
   * 文件重命名
   * @param {文件的全路径} fileFullPath
   * @param {文件新名称} name
   * @returns
   */
  rename(fileFullPath, name) {
    return request({
      url: `/file/rename`,
      method: "post",
      data: {
        name,
        path: fileFullPath,
      },
    });
  },
};
